//
//  AreaPickerView.m
//  picker
//
//  Created by 冷悦 on 16/4/25.
//  Copyright © 2016年 Sylar. All rights reserved.
//

#import "AreaPickerView.h"

typedef NS_ENUM(NSUInteger, AreaSection) {
    Province = 0,
    City = 1,
    District = 2
};

@interface AreaPickerView () <UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, strong)NSDictionary *areaDict;

@property (nonatomic, strong)NSArray *components;

@property (nonatomic, strong)NSArray *provinces;

@property (nonatomic, strong)NSArray *cities;

@property (nonatomic, strong)NSArray *districts;

@end

@implementation AreaPickerView

#pragma mark - Initialize
- (instancetype)init{
    if (self = [super init]) {
        self.dataSource = self;
        self.delegate = self;
    }
    
    return self;
}

- (instancetype)initWithSelectedAreaBlock:(SelectedArea)selectedAreaBlock{
    if (self = [self init] ) {
        self.backgroundColor = [UIColor whiteColor];
        if (selectedAreaBlock != nil) {
            self.selectedAreaBlock = selectedAreaBlock;
        }
    }
    
    return self;
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == Province) {
        return self.provinces.count;
    } else if (component == City){
        return self.cities.count;
    } else {
        return self.districts.count;
    }
}

#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == Province) {
        return [self.provinces objectAtIndex:row];
    } else if (component == City) {
        return [self.cities objectAtIndex:row];
    } else {
        return [self.districts objectAtIndex:row];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    if (component == Province) {
        return 80;
    } else if (component == City) {
        return 80;
    } else {
        return 80;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return [UIScreen mainScreen].bounds.size.height*0.07;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = nil;
    
    if (component == Province) {
        label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 70, 30)];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = [self.provinces objectAtIndex:row];
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:18];
        label.textColor = TextColor80;
        label.backgroundColor = [UIColor clearColor];
    }
    else if (component == City) {
        label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 70, 30)];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = [self.cities objectAtIndex:row];
        label.numberOfLines = 0;
        label.textColor = TextColor80;
        label.font = [UIFont systemFontOfSize:18];
        label.backgroundColor = [UIColor clearColor];
    }
    else {
        label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 70, 30)];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = [self.districts objectAtIndex:row];
        label.numberOfLines = 0;
        label.textColor = TextColor80;
        label.font = [UIFont systemFontOfSize:18];
        label.backgroundColor = [UIColor clearColor];
    }
    
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (component == Province) {
        _province = [self.provinces objectAtIndex:row];
        NSDictionary *tmp = [NSDictionary dictionaryWithDictionary:[self.areaDict objectForKey:[NSString stringWithFormat:@"%ld", row]]];
        NSDictionary *dict = [NSDictionary dictionaryWithDictionary:[tmp objectForKey:_province]];
        NSArray *cities = [dict allKeys];
        
        NSArray *cityArray = [cities sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            if ([obj1 integerValue] > [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([obj1 integerValue] > [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            
            return (NSComparisonResult)NSOrderedSame;
        }];
        
        NSMutableArray *array = [[NSMutableArray alloc]init];
        
        for (int i = 0; i < cityArray.count; i++) {
            NSString *index = [cityArray objectAtIndex:i];
            NSArray *tmp = [[dict objectForKey:index] allKeys];
            [array addObject:[tmp objectAtIndex:0]];
        }
        
        self.cities = [array copy];
        _city = [self.cities objectAtIndex:0];
        NSDictionary *cityDict = [dict objectForKey:[cityArray objectAtIndex:0]];
        self.districts = [[NSArray alloc]initWithArray:[cityDict objectForKey:[self.cities objectAtIndex:0]]];
        _district = [self.districts objectAtIndex:0];
        [self selectRow:0 inComponent:City animated:YES];
        [self selectRow:0 inComponent:District animated:YES];
        [self reloadComponent:City];
        [self reloadComponent:District];
    } else if (component == City) {
        _city = [self.cities objectAtIndex:row];
        NSString *provinceIndex = [NSString stringWithFormat:@"%ld", [self.provinces indexOfObject:_province]];
        NSDictionary *tmp = [NSDictionary dictionaryWithDictionary:[self.areaDict objectForKey:provinceIndex]];
        NSDictionary *dict = [NSDictionary dictionaryWithDictionary:[tmp objectForKey:_province]];
        NSArray *dictKeyArray = [dict allKeys];
        NSArray *dictArray = [dictKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            if ([obj1 integerValue] > [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([obj1 integerValue] > [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            
            return (NSComparisonResult)NSOrderedSame;
        }];
        
        NSDictionary *cityDict = [NSDictionary dictionaryWithDictionary:[dict objectForKey:[dictArray objectAtIndex:row]]];
        NSArray *cityKeyArray = [cityDict allKeys];
        self.districts = [[NSArray alloc] initWithArray:[cityDict objectForKey:[cityKeyArray objectAtIndex:0]]];
        _district = [self.districts objectAtIndex:0];
        [self selectRow:0 inComponent:District animated:YES];
        [self reloadComponent:District];
    } else {
        _district = [self.districts objectAtIndex:row];
    }
    
    if (self.selectedAreaBlock != nil) {
        NSDictionary *dict = @{@"province":_province, @"city":_city, @"district":_district};
        self.selectedAreaBlock(dict);
    }
    
}

#pragma mark Private
- (NSDictionary *)getCityDict{
    NSString *index = [self.components objectAtIndex:0];
    NSString *selected = [self.provinces objectAtIndex:0];
    NSDictionary *cityDictionary = [NSDictionary dictionaryWithDictionary:[[self.areaDict objectForKey:index] objectForKey:selected]];
    NSArray *cityArray = [cityDictionary allKeys];
    NSDictionary *cityDict = [NSDictionary dictionaryWithDictionary:[cityDictionary objectForKey:[cityArray objectAtIndex:0]]];
    
    return cityDict;
}

#pragma mark Getters
- (NSDictionary *)areaDict{
    if (_areaDict == nil) {
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *plistPath = [bundle pathForResource:@"area" ofType:@"plist"];
        _areaDict = [[NSDictionary alloc]initWithContentsOfFile:plistPath];
    }
    
    return _areaDict;
}

- (NSArray *)components{
    if (_components == nil) {
        _components = [self.areaDict allKeys];
        _components = [_components sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            if ([obj1 integerValue] > [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([obj1 integerValue] < [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            
            return (NSComparisonResult)NSOrderedSame;
        }];
    }
    
    return _components;
}

- (NSArray *)provinces{
    if (_provinces == nil) {
        NSMutableArray *provinces = [[NSMutableArray alloc]init];
        
        for (int i = 0; i < self.components.count; i++) {
            NSString *index = [self.components objectAtIndex:i];
            NSArray *tmpArray = [[self.areaDict objectForKey:index]allKeys];
            [provinces addObject:[tmpArray objectAtIndex:0]];
        }
        
        _provinces = [[NSArray alloc]initWithArray:provinces];
        _province = [_provinces objectAtIndex:0];
    }
    
    return _provinces;
}

- (NSArray *)cities{
    if (_cities == nil) {
        NSDictionary *cityDict = [self getCityDict];
        _cities = [[NSArray alloc]initWithArray:[cityDict allKeys]];
        _city = [_cities objectAtIndex:0];
    }
    
    return _cities;
}

- (NSArray *)districts{
    if (_districts == nil) {
        NSDictionary *cityDict = [self getCityDict];
        NSString *selectedCity = [self.cities objectAtIndex:0];
        _districts = [[NSArray alloc]initWithArray:[cityDict objectForKey:selectedCity]];
        _district = [_districts objectAtIndex:0];
    }
    
    return _districts;
}

@end
